<?php

namespace App\Services;

use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\Store;

class ProductService
{
    /** 以树形结构查询全部商品分类 */
    public function getCategoryTree($agentId)
    {
        return ProductCategory::query()
            ->with(['children'])
            ->where('parent_id', 0)
            ->where('agent_id', $agentId)
            ->orderBy('sequence')
            ->get()
            ->map(function (ProductCategory $category) {
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'children' => $category->children->map(function (ProductCategory $child) {
                        return [
                            'id' => $child->id,
                            'name' => $child->name,
                        ];
                    }),
                ];
            });
    }

    /** 查询代理商的商品查询条件 */
    public function getAgentProductQuery($agentId)
    {
        $agentStoreMobiles = Store::query()->where('agent_id', $agentId)
            ->select(['mobile'])
            ->distinct()
            ->pluck('mobile');

        return Product::query()
            ->where(function ($q) use ($agentId, $agentStoreMobiles) {
                return $q->where(function ($q1) use ($agentStoreMobiles) {
                    return $q1->whereIn('publisher_account', $agentStoreMobiles)->where('agent_id', 0);
                })->orWhere('agent_id', $agentId);
            });
    }
}
